﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
//using Fugle.Publics.BaseCode;
using System.Transactions;
//using Fugle.Publics.Entity;
//using Fugle.Interface.Enum;
using MemoryCacheExt;
using static Fugle.Win32API;
using OracleParameter = System.Data.OracleClient.OracleParameter;
using OracleType = System.Data.OracleClient.OracleType;
//using MemoryAccess;

namespace Fugle
{
    /// <summary>
    /// 数据访问进一步封装类
    /// </summary>
    public partial class FgSQL
    {

        /// <summary>
        /// 数据对象别名
        /// </summary>
        public string DBname;

        /// <summary>
        /// 构造
        /// </summary>
        //public FgSQL()
        //{
        //    DBname = FgPubConst.c_DbPublicConnection;
        //    ConnIsCheck();
        //}

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="_DBname">别名</param>
        public FgSQL(string _DBname)
        {
            DBname = _DBname;
            ConnIsCheck();
        }

        private void DBDispose(DbCommand _DbCommand)
        {
            try
            {
                if (_DbCommand != null)
                {
                    if (_DbCommand.Connection != null)
                    {
                        _DbCommand.Connection.Close();
                        _DbCommand.Connection.Dispose();
                    }
                    _DbCommand.Dispose();
                }
            }
            catch (Exception ex)
            {
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error("释放数据库资源出错[DBDispose]。", ex);
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", ex, "释放数据库资源出错[DBDispose]");
            }
        }


        #region 公用方法
        /// <summary>
        /// 获取表某个字段的最大值
        /// </summary>
        /// <param name="FieldName">数据表字段名</param>
        /// <param name="TableName">数据表名</param>
        /// <param name="ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>数据表传入字段最大值</returns>
        public int GetMaxID(string _FieldName, string _TableName)
        {
            return GetMaxID(_FieldName, _TableName, new StringBuilder());
        }

        /// <summary>
        /// 获取表某个字段的最大值
        /// </summary>
        /// <param name="_FieldName">数据表字段名</param>
        /// <param name="_TableName">数据表名</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>数据表传入字段最大值</returns>
        public int GetMaxID(string _FieldName, string _TableName, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgLogHelper.Write("获取" + _TableName + "表字段" + _FieldName + "最大长度。", "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            string _StrSql = "select max(" + _FieldName + ")+1 from " + _TableName;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            //var log = LogHelper.GetSqlLog(_StrSql,DBname,StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                object obj = DBNull.Value;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        obj = db.ExecuteScalar(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        obj = FgOracleHelperM.ExecuteScalar(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter> { });
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log,null);
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    return 1;
                else
                    return int.Parse(obj.ToString());
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error("获取" + _TableName + "表字段" + _FieldName + "最大长度。", e);
                //MemoryAccessWriteHelper.WriteStop(log, "获取" + _TableName + "表字段" + _FieldName + "最大长度。");
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, "获取" + _TableName + "表字段" + _FieldName + "最大长度。");
                FgLogHelper.Write("获取" + _TableName + "表字段" + _FieldName + "最大长度。", "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
            }
            finally { DBDispose(dbCommand); }
            return -1;
        }

        /// <summary>
        /// 检测一个记录是否存在(SQL语句方式)
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <returns>是否包含</returns>
        public bool Exists(string _StrSql)
        {
            return Exists(_StrSql, new StringBuilder());
        }

        /// <summary>
        /// 检测一个记录是否存在(SQL语句方式)
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns >是否包含</returns>
        public bool Exists(string _StrSql, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                object obj = DBNull.Value;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        obj = db.ExecuteScalar(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        obj = FgOracleHelperM.ExecuteScalar(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>());
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                int cmdresult;
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    cmdresult = 0;
                else
                    cmdresult = int.Parse(obj.ToString());

                return cmdresult == 0 ? false : true;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
            }
            finally { DBDispose(dbCommand); }
            return false;
        }

        /// <summary>
        ///  检测一个记录是否存在(SqlParameter语句方式)
        /// </summary>
        /// <param name="_StrSql">带参数SQL语句</param>
        /// <param name="_CmdParms">参数List<IDataParameter></param>
        /// <returns>是否包含</returns>
        public bool Exists(string _StrSql, List<IDataParameter> __CmdParms)
        {
            return Exists(_StrSql, __CmdParms, new StringBuilder());
        }

        /// <summary>
        ///  检测一个记录是否存在(SqlParameter语句方式)
        /// </summary>
        /// <param name="_StrSql">带参数SQL语句</param>
        /// <param name="_CmdParms">参数List<IDataParameter></param>
        /// <param name="ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>是否包含</returns>
        public bool Exists(string _StrSql, List<IDataParameter> _CmdParms, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                object obj = DBNull.Value;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        obj = db.ExecuteScalar(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        obj = FgOracleHelperM.ExecuteScalar(ConnStr, _StrSql, CommandType.Text, ref err, _CmdParms);
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                int cmdresult;
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    cmdresult = 0;
                else
                    cmdresult = int.Parse(obj.ToString());

                return cmdresult == 0 ? true : false;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
            }
            finally { DBDispose(dbCommand); }
            return false;
        }

        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="db">Database</param>
        /// <param name="dbCommand">DbCommand</param>
        /// <param name="_CmdParms">List<IDataParameter></param>
        public void BuildDBParameter(Database _Db, DbCommand _DbCommand, List<IDataParameter> _CmdParms)
        {
            foreach (IDataParameter sp in _CmdParms)
                _Db.AddInParameter(_DbCommand, sp.ParameterName, sp.DbType, sp.Value);
        }
        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteNonQuery(string _StrSql)
        {
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, new StringBuilder());
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                var Rt = -1;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        Rt = db.ExecuteNonQuery(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rt = FgOracleHelperM.ExecuteNonQuery2(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>());
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rt;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, new StringBuilder());
            }
            finally { DBDispose(dbCommand); }
            return -1;
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string _StrSql)
        {
            return ExecuteSql(_StrSql, new StringBuilder());
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string _StrSql, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                var Rt = -1;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        Rt = db.ExecuteNonQuery(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rt = FgOracleHelperM.ExecuteNonQuery(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>());
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rt;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
            }
            finally { DBDispose(dbCommand); }
            return -1;
        }

        public int ExecSqlTranXXX(List<string> _SQLStringList, List<IDataParameter> _CmdParms)
        {
            string _StrSql = "";
            foreach (string s in _SQLStringList)
            {
                _StrSql += s + "|";
            }

            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, new StringBuilder());
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            int count = 0;
            string ConnStr = string.Empty;
            switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
            {
                case EnumDBType.SQLDb:
                    Database db = new SqlDatabase(ConnStr);
                    DbConnection conn = db.CreateConnection();
                    conn.Open();
                    using (DbTransaction tran = conn.BeginTransaction())
                    {
                        try
                        {
                            for (int n = 0; n < _SQLStringList.Count; n++)
                            {
                                string _Sql = _SQLStringList[n];
                                if (_Sql.Trim().Length > 1)
                                {
                                    if (n == 0)
                                    {
                                        DbCommand dbCommand = null;
                                        dbCommand = db.GetSqlStringCommand(_Sql);
                                        BuildDBParameter(db, dbCommand, _CmdParms);
                                        count += db.ExecuteNonQuery(dbCommand, tran);
                                    }
                                    else
                                        count += db.ExecuteNonQuery(tran, CommandType.Text, _Sql);
                                }
                            }

                            // Commit the transaction 
                            tran.Commit();
                        }
                        catch (Exception e)
                        {
                            tran.Rollback();
                            new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                            //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                            //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                            FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, new StringBuilder());
                        }
                    }
                    break;
                case EnumDBType.OraDb:
                    try
                    {
                        string err = string.Empty;
                        string _StrSqlList = string.Empty;
                        for (int n = 0; n < _SQLStringList.Count; n++)
                            _StrSqlList += _SQLStringList[n] + "|";
                        var _ListIDataParameter = new List<List<IDataParameter>>();
                        foreach (IDataParameter _par in _CmdParms)
                            _ListIDataParameter.Add(new List<IDataParameter>() { _par });
                        count = FgOracleHelperM.ExecuteNonQueryTransaction(ConnStr, _SQLStringList, CommandType.Text, ref err, _ListIDataParameter);
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err + "SQL：" + _StrSqlList);
                    }
                    catch (Exception e)
                    {
                        new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                        //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                        //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                        FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, new StringBuilder());
                    }
                    break;
            }
            TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
            return count;
        }


        /// <summary>
        /// 执行SQL语句，返回影响的记录数(对于长时间查询的语句，设置等待时间避免查询超时)
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Times">等待时间</param>
        /// <returns>返回影响行数</returns>
        public int ExecuteSqlByTimeout(string _StrSql, int _Times)
        {
            return ExecuteSqlByTimeout(_StrSql, _Times, new StringBuilder());
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数(对于长时间查询的语句，设置等待时间避免查询超时)
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Times">等待时间</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>返回影响行数</returns>
        public int ExecuteSqlByTimeout(string _StrSql, int _Times, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                var Rt = -1;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        dbCommand.CommandTimeout = _Times;
                        Rt = db.ExecuteNonQuery(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rt = FgOracleHelperM.ExecuteNonQuery(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>(), _Times);
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }

                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rt;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="_SQLStringList">多条SQL语句</param>     
        public int ExecuteSqlList(ArrayList _SQLStringList)
        {
            return ExecuteSqlList(_SQLStringList, new StringBuilder());
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="_SQLStringList">多条SQL语句</param>     
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        public int ExecuteSqlList(ArrayList _SQLStringList, StringBuilder _ExtendInfo)
        {
            var listSql = new List<string>();
            for (int i = 0; i < _SQLStringList.Count; i++)
                listSql.Add(_SQLStringList[i].ToString());
            return ExecSqlTran(listSql, _ExtendInfo);
        }



        #region 执行一个特殊字段带参数的语句

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string _StrSql, string _Content)
        {
            return ExecuteSql(_StrSql, _Content, new StringBuilder());
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string _StrSql, string _Content, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                var Rt = -1;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        db.AddInParameter(dbCommand, "@content", DbType.String, _Content);
                        Rt = db.ExecuteNonQuery(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rt = FgOracleHelperM.ExecuteNonQuery(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>() {
                            new System.Data.OracleClient.OracleParameter() {
                                ParameterName=":content",
                                 Value = _Content,
                                 //OracleDbType = Oracle.ManagedDataAccess.Client.OracleDbType.NVarchar2,
                                  Direction = ParameterDirection.Input
                            }
                        });
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rt;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>返回语句里的查询结果</returns>
        public object ExecuteSqlGet(string _StrSql, string _Content)
        {
            return ExecuteSqlGet(_StrSql, _Content, new StringBuilder());
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>返回语句里的查询结果</returns>
        public object ExecuteSqlGet(string _StrSql, string _Content, StringBuilder _ExtendInfo)
        {
            return ExecuteSql(_StrSql, _Content, _ExtendInfo);
        }

        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSqlInsertImg(string _StrSql, byte[] _Fs)
        {
            return ExecuteSqlInsertImg(_StrSql, _Fs, new StringBuilder());
        }

        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Fs">图像字节,数据库的字段类型为image的情况</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSqlInsertImg(string _StrSql, byte[] _Fs, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                var Rt = -1;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        db.AddInParameter(dbCommand, "@fs", DbType.Byte, _Fs);
                        Rt = db.ExecuteNonQuery(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rt = FgOracleHelperM.ExecuteNonQuery(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>() {
                            new System.Data.OracleClient.OracleParameter() {
                                ParameterName=":fs",
                                 Value = _Fs,
                                 //OracleDbType = Oracle.ManagedDataAccess.Client.OracleDbType.Blob,
                                  Direction = ParameterDirection.Input
                            }
                        });
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }

                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rt;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }
        #endregion

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="_StrSql">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string _StrSql)
        {
            return GetSingle(_StrSql, new StringBuilder());
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="_StrSql">计算查询结果语句</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string _StrSql, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                object obj = DBNull.Value;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        obj = db.ExecuteScalar(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        obj = FgOracleHelperM.ExecuteScalar(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>());
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    return null;
                else
                    return obj;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行查询语句，返回DbDataReader ( 注意：使用后一定要对DbDataReader进行Close )
        /// </summary>
        /// <param name="_StrSql">查询语句</param>
        /// <returns>IDataReader</returns>
        public IDataReader ExecuteReader(string _StrSql)
        {
            return ExecuteReader(_StrSql, new StringBuilder());
        }

        /// <summary>
        /// 执行查询语句，返回DbDataReader ( 注意：使用后一定要对DbDataReader进行Close )
        /// </summary>
        /// <param name="_StrSql">查询语句</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>IDataReader</returns>
        public IDataReader ExecuteReader(string _StrSql, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                IDataReader dr = null;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        dr = (IDataReader)db.ExecuteReader(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        dr = FgOracleHelperM.ExecuteReader(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>());
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return dr;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 获取存储过程参数
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <returns>object[]</returns>
        private object[] GetParameters(string _StrSql)
        {
            string spname = _StrSql.Substring(0, _StrSql.IndexOf("(")).Trim();

            ArrayList _args = new ArrayList();

            if (_StrSql.IndexOf(',') != -1)
            {
                string sppara = _StrSql.Substring(_StrSql.IndexOf("(") + 1).Trim().Replace(",cur_OUT)", "");
                List<string> _para = sppara.Split(',').ToList();

                bool flag = false;

                _para.ForEach(p =>
                {
                    int _count = ((p.ToCharArray().ToList().FindAll(g => g == (char)39))).Count;
                    if ((_count % 2 == 0 || p.IndexOf((char)39) == -1) && !flag)
                    {
                        if (p.Trim().ToUpper() == "NULL")
                        {
                            _args.Add(null);
                        }
                        else
                        {
                            _args.Add(p.Trim().Replace("'", ""));
                        }
                    }
                    else if (_count % 2 != 0 && !flag)
                    {
                        _args.Add(p + ",");
                        flag = true;
                    }
                    else if (_count % 2 != 0 && flag)
                    {
                        _args[_args.Count - 1] += p;
                        string tmp = string.Empty;
                        tmp = _args[_args.Count - 1].ToString();
                        _args[_args.Count - 1] = tmp.Substring(1, tmp.Length - 2).Replace("''", "'");
                        flag = false;
                    }
                    else
                    {
                        _args[_args.Count - 1] += p + ',';
                    }
                });
            }
            //_args.Add(null); // "cur_OUT"
            return _args.ToArray();
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="_StrSql">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string _StrSql)
        {
            return Query(_StrSql, new StringBuilder());
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="_StrSql">查询语句</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string _StrSql, StringBuilder _ExtendInfo)
        {
            DataSet ds = new DataSet();
            DbCommand dbCommand = null;
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
                FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);

                object obj = DBNull.Value;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        if (_StrSql.IndexOf("cur_OUT") > -1)
                        {
                            using (DbConnection conn = db.CreateConnection())
                            {
                                conn.Open();
                                DbTransaction tran = conn.BeginTransaction();
                                string spname = _StrSql.Substring(0, _StrSql.IndexOf("(")).Trim();
                                object[] _args = GetParameters(_StrSql);

                                dbCommand = db.GetStoredProcCommand(spname, _args);
                                dbCommand.Transaction = tran;
                                try
                                {
                                    ds = db.ExecuteDataSet(dbCommand, tran);
                                    tran.Commit();
                                }
                                catch (Exception e)
                                {
                                    tran.Rollback();
                                    throw new Exception(e.Message);
                                }
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(_StrSql))
                            {
                                dbCommand = db.GetSqlStringCommand(_StrSql);
                                ds = db.ExecuteDataSet(dbCommand);
                            }
                        }
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        if (_StrSql.IndexOf("cur_OUT") > -1)
                        {
                            var listOracleParameter = new List<IDataParameter>();
                            string spname = _StrSql.Substring(0, _StrSql.IndexOf("(")).Trim();
                            if (spname.Contains("."))
                                spname = spname.Split('.')[1];
                            object[] _args = GetParameters(_StrSql);
                            foreach (var value in _args)
                                listOracleParameter.Add(new System.Data.OracleClient.OracleParameter() { Direction = ParameterDirection.Input, Value = value });
                            listOracleParameter.Add(new System.Data.OracleClient.OracleParameter()
                            {
                                Direction = ParameterDirection.Output,
                                OracleType =  OracleType.Cursor
                            });
                            ds = FgOracleHelperM.Query(ConnStr, spname, CommandType.StoredProcedure, ref err, listOracleParameter);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(_StrSql))
                                ds = FgOracleHelperM.Query(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>());
                        }
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return ds;
            }
            catch (Exception e)
            {
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw new Exception(e.Message);
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// (对于长时间查询的语句，设置等待时间避免查询超时)
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Times">超时时间</param>
        /// <returns>返回DataSet影响行数</returns>
        public DataSet Query(string _StrSql, int _Times)
        {
            return Query(_StrSql, _Times, new StringBuilder());
        }

        /// <summary>
        /// (对于长时间查询的语句，设置等待时间避免查询超时)
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_Times">超时时间</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>返回DataSet影响行数</returns>
        public DataSet Query(string _StrSql, int _Times, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            DataSet Rds = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        dbCommand.CommandTimeout = _Times;
                        Rds = db.ExecuteDataSet(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rds = FgOracleHelperM.Query(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>(), _Times);
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rds;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
               // FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw new Exception(e.Message);
            }
            finally { DBDispose(dbCommand); }
        }
        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数 语句中实现:SQL参数传入":+参数名",ORACLE参数传入"@+参数名"
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string _StrSql, List<IDataParameter> __CmdParms)
        {
            return ExecuteSql(_StrSql, __CmdParms, new StringBuilder());
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数 语句中实现:SQL参数传入":+参数名",ORACLE参数传入"@+参数名"
        /// </summary>
        /// <param name="_StrSql">SQL语句</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string _StrSql, List<IDataParameter> _CmdParms, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                var Rt = -1;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        BuildDBParameter(db, dbCommand, _CmdParms);
                        Rt = db.ExecuteNonQuery(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rt = FgOracleHelperM.ExecuteNonQuery(ConnStr, _StrSql, CommandType.Text, ref err, _CmdParms);
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }

                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rt;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw new Exception(e.Message);
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="_SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public void ExecuteSqlHashtable(Hashtable _SQLStringList)
        {
            ExecuteSqlHashtable(_SQLStringList, new StringBuilder());
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="_SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        public void ExecuteSqlHashtable(Hashtable _SQLStringList, StringBuilder _ExtendInfo)
        {
            string _StrSql = "";
            if (_SQLStringList != null)
            {
                foreach (DictionaryEntry _DictionaryEntry in _SQLStringList)
                {
                    _StrSql += _DictionaryEntry.Key + "   ";
                    foreach (SqlParameter _SqlParameter in (SqlParameter[])_DictionaryEntry.Value)
                    {
                        _StrSql += _SqlParameter.ParameterName + "(" + _SqlParameter.DbType + ")[" + _SqlParameter.Value + "]";
                    }
                    _StrSql += "|\r\t";
                }
            }
            DbCommand dbCommand = null;
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        //执行语句
                        foreach (DictionaryEntry myDE in _SQLStringList)
                        {
                            string _Sql = myDE.Key.ToString();
                            List<IDataParameter> _CmdParms = (List<IDataParameter>)myDE.Value;
                            if (_Sql.Trim().Length > 1)
                            {
                                dbCommand = db.GetSqlStringCommand(_Sql);
                                BuildDBParameter(db, dbCommand, _CmdParms);
                                db.ExecuteNonQuery(dbCommand);
                                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                                //MemoryAccessWriteHelper.WriteStop(log);
                            }
                        }
                        break;
                    case EnumDBType.OraDb:
                        var err = string.Empty;
                        var listsql = new List<string>();
                        var listParameters = new List<List<IDataParameter>>();
                        foreach (DictionaryEntry myDE in _SQLStringList)
                        {
                            listsql.Add(myDE.Key as string);
                            listParameters.Add((List<IDataParameter>)myDE.Value);
                        }
                        FgOracleHelperM.ExecuteNonQueryTransaction(ConnStr, listsql, CommandType.Text, ref err, listParameters);
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err + "SQL：" + _StrSql);
                        else
                        {
                            TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                            //MemoryAccessWriteHelper.WriteStop(log);
                        }
                        break;
                }
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="_StrSql">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string _StrSql, List<IDataParameter> _CmdParms)
        {
            return GetSingle(_StrSql, _CmdParms, new StringBuilder());
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="_StrSql">计算查询结果语句</param>
        /// <param name="_ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string _StrSql, List<IDataParameter> _CmdParms, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                object obj = DBNull.Value;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        BuildDBParameter(db, dbCommand, _CmdParms);
                        obj = db.ExecuteScalar(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        obj = FgOracleHelperM.ExecuteScalar(ConnStr, _StrSql, CommandType.Text, ref err, new List<IDataParameter>());
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    return null;
                else
                    return obj;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader ( 注意：使用后一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="_StrSql">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public SqlDataReader ExecuteReader(string _StrSql, List<IDataParameter> _CmdParms)
        {
            return ExecuteReader(_StrSql, _CmdParms, new StringBuilder());
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader ( 注意：(SqlServer数据库专用)使用后一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="_StrSql">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public SqlDataReader ExecuteReader(string _StrSql, List<IDataParameter> _CmdParms, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                string ConnStr = string.Empty;
                GetDBTypeAndConnStr(DBname, ref ConnStr);
                Database db = new SqlDatabase(ConnStr);
                dbCommand = db.GetSqlStringCommand(_StrSql);
                BuildDBParameter(db, dbCommand, _CmdParms);
                SqlDataReader dr = (SqlDataReader)db.ExecuteReader(dbCommand);
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return dr;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw new Exception(e.Message);
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="_StrSql">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string _StrSql, List<IDataParameter> _CmdParms)
        {
            return Query(_StrSql, _CmdParms, new StringBuilder());
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="_StrSql">查询语句</param>
        /// <param name="ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string _StrSql, List<IDataParameter> _CmdParms, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StrSql, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                DataSet Rds = new DataSet();
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetSqlStringCommand(_StrSql);
                        BuildDBParameter(db, dbCommand, _CmdParms);
                        Rds = db.ExecuteDataSet(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rds = FgOracleHelperM.Query(ConnStr, _StrSql, CommandType.Text, ref err, _CmdParms);
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rds;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 使用外部传入的SqlTransaction，实现数据库事务
        /// </summary>
        /// <param name="_Cmd">SqlCommand</param>
        /// <param name="_Conn">SqlConnection</param>
        /// <param name="_Trans">SqlTransaction</param>
        /// <param name="_CmdText">cmdText</param>
        /// <param name="_CmdParms">SqlParameter[]</param>
        private void PrepareCommand(SqlCommand _Cmd, SqlConnection _Conn, SqlTransaction _Trans, string _CmdText, SqlParameter[] _CmdParms)
        {
            if (_Conn.State != ConnectionState.Open)
                _Conn.Open();
            _Cmd.Connection = _Conn;
            _Cmd.CommandText = _CmdText;
            if (_Trans != null)
                _Cmd.Transaction = _Trans;
            _Cmd.CommandType = CommandType.Text;//cmdType;
            if (_CmdParms != null)
            {
                foreach (SqlParameter parameter in _CmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                         (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    _Cmd.Parameters.Add(parameter);
                }
            }
        }

        /// <summary>
        /// 数据库事务
        /// </summary>
        /// <param name="_pList"></param>
        /// <param name="_dbName"></param>
        /// <returns></returns>
        public bool ExecSqlList(ref List<SqlEntity> _pList, string _dbName)
        {
            /*创建执行事务的数据库和连接*/
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            string ConnStr = string.Empty;
            var _StrSqlList = string.Empty;
            //var log = LogHelper.GetSqlLog("执行事务中", DBname, StackTraceHelper.GetStackTrace());
            //log.IsTran = true;
            //MemoryAccessWriteHelper.Write(log);
            switch (GetDBTypeAndConnStr(_dbName, ref ConnStr))
            {
                case EnumDBType.SQLDb:
                    var db = DatabaseFactory.CreateDatabase(_dbName);
                    var conn = db.CreateConnection();
                    DbCommand dbCommand = null;
                    DbTransaction tran = null;
                    try
                    {
                        conn.Open();
                        using (tran = conn.BeginTransaction())
                        {
                            for (int i = 0; i < _pList.Count; i++)
                            {
                                _StrSqlList += _pList[i].sql + "|";
                                if (_pList[i].Paras != null)
                                {
                                    dbCommand = db.GetSqlStringCommand(_pList[i].sql);
                                    dbCommand.Connection = conn;
                                    dbCommand.Transaction = tran;
                                    BuildDBParameter(db, dbCommand, _pList[i].Paras);
                                    dbCommand.ExecuteNonQuery();//执行sql语句 2014-01-03
                                    //_pList[i].ds = db.ExecuteDataSet(dbCommand);
                                    GetOutputParaVal(db, dbCommand, _pList[i].ds, ref _pList[i].Paras);
                                }
                                else
                                {
                                    _pList[i].count = db.ExecuteNonQuery(CommandType.Text, _pList[i].sql);
                                }
                            }
                            tran.Commit();
                            TimeOutLog(_StrSqlList, _FgFuncQueryTime.Calculate());
                            //log.Sql = _StrSqlList;
                            //MemoryAccessWriteHelper.WriteStop(log);
                            return true;
                        }
                    }
                    catch (Exception e)
                    {
                        TimeOutLog(_StrSqlList, _FgFuncQueryTime.Calculate());
                        //log.Sql = _StrSqlList;
                        //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                        if (conn.State != ConnectionState.Closed) { tran.Rollback(); }
                        throw e;
                    }
                    finally { DBDispose(dbCommand); }
                case EnumDBType.OraDb:
                    try
                    {
                        var res = FgOracleHelperM.ExecSqlList(ref _pList, ConnStr);
                        //log.Sql = string.Join("|", _pList);
                        //MemoryAccessWriteHelper.WriteStop(log);
                        return res;
                    }
                    catch (Exception e)
                    {
                        TimeOutLog(_StrSqlList, _FgFuncQueryTime.Calculate());
                        new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSqlList, e);
                        //log.Sql = string.Join("|", _pList);
                        //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                        //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSqlList);
                        throw;
                    }
            }
            return true;

        }


        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="_SQLStringList">多条SQL语句</param>		
        public int ExecSqlTran(List<string> _SQLStringList)
        {
            return ExecSqlTran(_SQLStringList, new StringBuilder());
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="_SQLStringList">多条SQL语句</param>	
        /// <param name="ExtendInfo">扩展消息 长度限制：100字节内</param>
        public int ExecSqlTran(List<string> _SQLStringList, StringBuilder _ExtendInfo)
        {
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            int count = 0;
            var _StrSqlList = string.Empty;
            string ConnStr = string.Empty;
            //var log = LogHelper.GetSqlLog("执行事务中", DBname, StackTraceHelper.GetStackTrace());
            //log.IsTran = true;
            //MemoryAccessWriteHelper.Write(log);
            switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
            {
                case EnumDBType.SQLDb:
                    Database db = new SqlDatabase(ConnStr);
                    DbConnection conn = db.CreateConnection();
                    conn.Open();
                    using (DbTransaction tran = conn.BeginTransaction())
                    {
                        try
                        {
                            for (int n = 0; n < _SQLStringList.Count; n++)
                            {
                                string _Sql = _SQLStringList[n];
                                _StrSqlList += _Sql + "|";
                                if (_Sql.Trim().Length > 1)
                                {
                                    count += db.ExecuteNonQuery(tran, CommandType.Text, _Sql);
                                }
                            }
                            tran.Commit();
                            FgLogHelper.Write(_StrSqlList, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
                            //log.Sql = _StrSqlList;
                            //MemoryAccessWriteHelper.WriteStop(log);
                        }
                        catch (Exception e)
                        {
                            TimeOutLog(_StrSqlList, _FgFuncQueryTime.Calculate());
                            tran.Rollback();
                            new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSqlList, e);
                            //log.Sql = _StrSqlList;
                            //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                            //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSqlList);
                            FgLogHelper.Write(_StrSqlList, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                            throw;
                        }
                    }
                    break;
                case EnumDBType.OraDb:
                    try
                    {
                        string err = string.Empty;
                        for (int n = 0; n < _SQLStringList.Count; n++)
                            _StrSqlList += _SQLStringList[n] + "|";
                        count = FgOracleHelperM.ExecuteNonQueryTransaction(ConnStr, _SQLStringList, CommandType.Text, ref err, new List<List<IDataParameter>>() { });
                        //log.Sql = _StrSqlList;
                        //MemoryAccessWriteHelper.WriteStop(log);
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err + "SQL：" + _StrSqlList);
                    }
                    catch (Exception e)
                    {
                        TimeOutLog(_StrSqlList, _FgFuncQueryTime.Calculate());
                        new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSqlList, e);
                        //log.Sql = _StrSqlList;
                        //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                        //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSqlList);
                        FgLogHelper.Write(_StrSqlList, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                        throw;
                    }
                    break;
            }
            TimeOutLog(_StrSqlList, _FgFuncQueryTime.Calculate());
            return count;
        }

        /// <summary>
        /// 执行2个数据库多条SQL语句，实现多个数据库事务。
        /// </summary>
        /// <param name="_DBname1">数据库别名1</param>
        /// <param name="_SQLStringList1">使用别名1执行的多条语句</param>
        /// <param name="_DBname2">数据库别名2</param>
        /// <param name="_SQLStringList2">使用别名2执行的多条语句</param>
        /// <param name="ExtendInfo">日志扩展文本</param>
        /// <returns></returns>
        public int ExecSqlTran(string _DBname1, List<string> _SQLStringList1, string _DBname2, List<string> _SQLStringList2, StringBuilder _ExtendInfo)
        {
            string _StrSql = "";
            foreach (string s in _SQLStringList1)
                _StrSql += s + "|";

            foreach (string s in _SQLStringList2)
                _StrSql += s + "|";

            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            Database db1 = DatabaseFactory.CreateDatabase(_DBname1);
            DbConnection conn1 = db1.CreateConnection();
            conn1.Open();

            Database db2 = DatabaseFactory.CreateDatabase(_DBname2);
            DbConnection conn2 = db2.CreateConnection();
            conn2.Open();

            using (DbTransaction tran1 = conn1.BeginTransaction())
            {
                using (DbTransaction tran2 = conn2.BeginTransaction())
                {
                    int count = 0;
                    try
                    {
                        for (int n = 0; n < _SQLStringList1.Count; n++)
                        {
                            string _Sql = _SQLStringList1[n];
                            if (_Sql.Trim().Length > 1)
                                count += db1.ExecuteNonQuery(tran1, CommandType.Text, _Sql);
                        }

                        for (int n = 0; n < _SQLStringList2.Count; n++)
                        {
                            string _Sql = _SQLStringList2[n];
                            if (_Sql.Trim().Length > 1)
                                count += db2.ExecuteNonQuery(tran2, CommandType.Text, _Sql);
                        }

                        // Commit the transaction 
                        tran1.Commit();
                        // Commit the transaction 
                        tran2.Commit();
                        TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                    }
                    catch (Exception e)
                    {
                        TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                        // Rollback transaction 
                        new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                        //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                        FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                        count = -1;
                        tran1.Rollback();
                        tran2.Rollback();
                        return count;
                    }

                    return count;
                }
            }
        }
        #endregion

        #region 存储过程操作

        /// <summary>
        /// 执行存储过程，返回影响的行数
        /// </summary>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <returns>影响行数</returns>
        public int RunProcedure(string _StoredProcName)
        {
            return RunProcedure(_StoredProcName, new StringBuilder());
        }

        /// <summary>
        /// 执行存储过程，返回影响的行数
        /// </summary>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <param name="ExtendInfo">扩展消息 长度限制：100字节内</param>
        /// <returns>影响行数</returns>
        public int RunProcedure(string _StoredProcName, StringBuilder _ExtendInfo)
        {
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write("执行存储过程：" + _StoredProcName, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StoredProcName, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                var Rt = -1;
                string ConnStr = string.Empty;
                switch (GetDBTypeAndConnStr(DBname, ref ConnStr))
                {
                    case EnumDBType.SQLDb:
                        Database db = new SqlDatabase(ConnStr);
                        dbCommand = db.GetStoredProcCommand(_StoredProcName);
                        Rt = db.ExecuteNonQuery(dbCommand);
                        break;
                    case EnumDBType.OraDb:
                        string err = string.Empty;
                        Rt = FgOracleHelperM.ExecuteNonQuery(ConnStr, _StoredProcName, CommandType.StoredProcedure, ref err, new List<IDataParameter>() { });
                        if (!string.IsNullOrEmpty(err)) throw new Exception(err);
                        break;
                }
                TimeOutLog(_StoredProcName, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rt;
            }
            catch (Exception e)
            {
                TimeOutLog(_StoredProcName, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error("执行存储过程：" + _StoredProcName + "FgSQL异常", e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, "执行存储过程：" + _StoredProcName + "FgSQL异常");
                FgLogHelper.Write("执行存储过程：" + _StoredProcName, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行存储过程，返回输出参数的值和影响的行数       
        /// </summary>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="_OutParameter">输出参数名称</param>
        /// <param name="_RowsAffected">影响的行数</param>
        /// <param name="OutParameterSize">返回参数数据包大小(字节计算)</param>
        /// <returns>object</returns>
        public object RunProcedure(string _StoredProcName, List<IDataParameter> _InParameters, IDataParameter _OutParameter, int _RowsAffected, int _OutParameterSize)
        {
            return RunProcedure(_StoredProcName, _InParameters, _OutParameter, _RowsAffected, _OutParameterSize, new StringBuilder());
        }

        /// <summary>
        /// 执行存储过程，返回输出参数的值和影响的行数       
        /// </summary>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="_OutParameter">输出参数名称</param>
        /// <param name="_RowsAffected">影响的行数</param>
        /// <param name="_OutParameterSize">返回参数数据包大小(字节计算)</param>
        /// <returns>object</returns>
        public object RunProcedure(string _StoredProcName, List<IDataParameter> _InParameters, IDataParameter _OutParameter, int _RowsAffected, int _OutParameterSize, StringBuilder _ExtendInfo)
        {
            string _StrSql = "";
            _StrSql += "执行存储过程：" + _StoredProcName;
            if (_InParameters != null)
            {
                _StrSql += "  入参：";
                foreach (IDataParameter _IDataParameter in _InParameters)
                    _StrSql += _IDataParameter.ParameterName + "(" + _IDataParameter.DbType + ")[" + _IDataParameter.Value + "] ";
            }
            if (_OutParameter != null)
                _StrSql += "  出参：" + _OutParameter.ParameterName + "(" + _OutParameter.DbType + ")[" + _OutParameter.Value + "] ";
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StoredProcName, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                string ConnStr = string.Empty;
                GetDBTypeAndConnStr(DBname, ref ConnStr);
                Database db = new SqlDatabase(ConnStr);
                dbCommand = db.GetStoredProcCommand(_StoredProcName);
                BuildDBParameter(db, dbCommand, _InParameters);
                db.AddOutParameter(dbCommand, _OutParameter.ParameterName, _OutParameter.DbType, _OutParameterSize);
                _RowsAffected = db.ExecuteNonQuery(dbCommand);
                object Rtb = db.GetParameterValue(dbCommand, "@" + _OutParameter.ParameterName);  //得到输出参数的值
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rtb;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行存储过程，返回SqlDataReader ( 注意：使用后一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <param name="_Parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public SqlDataReader RunProcedure(string _StoredProcName, IDataParameter[] _Parameters)
        {
            return RunProcedure(_StoredProcName, _Parameters, new StringBuilder());
        }

        /// <summary>
        /// 执行存储过程，返回SqlDataReader ( 注意：使用后一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <param name="_Parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public SqlDataReader RunProcedure(string _StoredProcName, IDataParameter[] _Parameters, StringBuilder _ExtendInfo)
        {
            string _StrSql = "";
            _StrSql += "执行存储过程：" + _StoredProcName;
            if (_Parameters != null)
            {
                _StrSql += "  入参：";
                foreach (IDataParameter _IDataParameter in _Parameters)
                    _StrSql += _IDataParameter.ParameterName + "(" + _IDataParameter.DbType + ")[" + _IDataParameter.Value + "] ";
            }
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StoredProcName, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                string ConnStr = string.Empty;
                GetDBTypeAndConnStr(DBname, ref ConnStr);
                Database db = new SqlDatabase(ConnStr);
                dbCommand = db.GetStoredProcCommand(_StoredProcName, _Parameters);
                SqlDataReader RSqlDataReader = (SqlDataReader)db.ExecuteReader(dbCommand);
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return RSqlDataReader;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行存储过程，返回DataSet
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="_TableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public DataSet RunProcedure(string _StoredProcName, IDataParameter[] _Parameters, string _TableName)
        {
            return RunProcedure(_StoredProcName, _Parameters, _TableName, new StringBuilder());
        }

        /// <summary>
        /// 执行存储过程，返回DataSet
        /// </summary>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <param name="_Parameters">存储过程参数</param>
        /// <param name="_TableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public DataSet RunProcedure(string _StoredProcName, IDataParameter[] _Parameters, string _TableName, StringBuilder _ExtendInfo)
        {
            string _StrSql = "";
            _StrSql += "执行存储过程：" + _StoredProcName;
            if (_Parameters != null)
            {
                _StrSql += "  入参：";
                foreach (IDataParameter _IDataParameter in _Parameters)
                    _StrSql += _IDataParameter.ParameterName + "(" + _IDataParameter.DbType + ")[" + _IDataParameter.Value + "] ";
            }
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            //var log = LogHelper.GetSqlLog(_StoredProcName, DBname, StackTraceHelper.GetStackTrace());
            //MemoryAccessWriteHelper.Write(log);
            try
            {
                string ConnStr = string.Empty;
                GetDBTypeAndConnStr(DBname, ref ConnStr);
                Database db = new SqlDatabase(ConnStr);
                dbCommand = db.GetStoredProcCommand(_StoredProcName, _Parameters);
                DataSet Rds = db.ExecuteDataSet(dbCommand);
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                //MemoryAccessWriteHelper.WriteStop(log);
                return Rds;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //MemoryAccessWriteHelper.WriteStop(log,e.ToString());
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 执行存储过程，返回DataSet(设定等待时间)
        /// </summary>
        /// <param name="_StoredProcName">storedProcName</param>
        /// <param name="parameters">IDataParameter[]</param>
        /// <param name="_TableName">表名</param>
        /// <param name="_Times">超时时间</param>
        /// <returns>返回影响DataSet</returns>
        public DataSet RunProcedure(string _StoredProcName, IDataParameter[] _Parameters, string _TableName, int _Times)
        {
            return RunProcedure(_StoredProcName, _Parameters, _TableName, _Times);
        }

        /// <summary>
        /// 执行存储过程，返回DataSet(设定等待时间)
        /// </summary>
        /// <param name="_StoredProcName">storedProcName</param>
        /// <param name="_Parameters">IDataParameter[]</param>
        /// <param name="tableName">表名</param>
        /// <param name="_Times">超时时间</param>
        /// <returns>返回影响DataSet</returns>
        public DataSet RunProcedure(string _StoredProcName, IDataParameter[] _Parameters, string _TableName, int _Times, StringBuilder _ExtendInfo)
        {
            string _StrSql = "";
            _StrSql += "执行存储过程：" + _StoredProcName;
            if (_Parameters != null)
            {
                _StrSql += "  入参：";
                foreach (IDataParameter _IDataParameter in _Parameters)
                    _StrSql += _IDataParameter.ParameterName + "(" + _IDataParameter.DbType + ")[" + _IDataParameter.Value + "] ";
            }
            DbCommand dbCommand = null;
            FgFuncQueryTime _FgFuncQueryTime = new FgFuncQueryTime();
            FgLogHelper.Write(_StrSql, "FgSQL常规", EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
            try
            {
                string ConnStr = string.Empty;
                GetDBTypeAndConnStr(DBname, ref ConnStr);
                Database db = new SqlDatabase(ConnStr);
                dbCommand = db.GetStoredProcCommand(_StoredProcName, _Parameters);
                dbCommand.CommandTimeout = _Times;
                DataSet Rds = db.ExecuteDataSet(dbCommand);
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                return Rds;
            }
            catch (Exception e)
            {
                TimeOutLog(_StrSql, _FgFuncQueryTime.Calculate());
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error(_StrSql, e);
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, _StrSql);
                FgLogHelper.Write(_StrSql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error, _ExtendInfo);
                throw;
            }
            finally { DBDispose(dbCommand); }
        }

        /// <summary>
        /// 构建SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="_Connection">数据库连接</param>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <param name="_Parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private SqlCommand BuildQueryCommand(SqlConnection _Connection, string _StoredProcName, IDataParameter[] _Parameters)
        {
            SqlCommand command = new SqlCommand(_StoredProcName, _Connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in _Parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                         (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

        /// <summary>
        /// 创建SqlCommand 对象实例(用来返回一个整数值)    
        /// </summary>
        /// <param name="_Connection">SqlConnection</param>
        /// <param name="_StoredProcName">存储过程名</param>
        /// <param name="_StoredProcName">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private SqlCommand BuildIntCommand(SqlConnection _Connection, string _StoredProcName, IDataParameter[] _Parameters)
        {
            SqlCommand command = BuildQueryCommand(_Connection, _StoredProcName, _Parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                 SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                 false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }
        #endregion

        #region 跨数据库执行事务

        /// <summary>
        /// 跨数据库执行事务
        /// </summary>
        /// <param name="_List"></param>
        /// <returns></returns>
        public bool ExecSqlList(ref List<SqlEntity> _List)
        {
            int i = 0;
            var obj = _List.GroupBy(p => new { p.DbName, p.conn, p.tran, p.db });
            try
            {
                TransactionOptions options = new TransactionOptions();
                options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                options.Timeout = new TimeSpan(0, 2, 0);
                // 创建事务
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
                {
                    // 创建连接
                    foreach (var database in obj)
                    {
                        foreach (var item in database.ToList())
                        {
                            item.db = DatabaseFactory.CreateDatabase(database.Key.DbName);
                            item.conn = item.db.CreateConnection();
                            item.conn.Open();
                        }
                    }
                    for (i = 0; i < _List.Count; i++)
                    {
                        if (_List[i].Paras != null)
                        {
                            DbCommand dbCommand = _List[i].db.GetSqlStringCommand(_List[i].sql);
                            dbCommand.Connection = _List[i].conn;

                            BuildDBParameter(_List[i].db, dbCommand, _List[i].Paras);

                            _List[i].ds = _List[i].db.ExecuteDataSet(dbCommand);
                            GetOutputParaVal(_List[i].db, dbCommand, _List[i].ds, ref _List[i].Paras);
                        }
                        else
                        {
                            _List[i].count = _List[i].db.ExecuteNonQuery(CommandType.Text, _List[i].sql);
                        }

                        // 让用户控制是否回滚
                        SqlEvent se = new SqlEvent(i, _List[i].sql, _List[i].Paras, _List[i].count);
                        if (Sqlcommit != null) Sqlcommit(se);
                        if (se.NeedRollback == true) throw new Exception("NeedRollback");
                    }

                    // 提交事务
                    scope.Complete();
                }
                return true;
            }
            catch (Exception e)
            {
                new FgLogHelperPro(DBname + "_SQL异常信息").Write.Error("[" + _List[i].DbName + "]:" + _List[i].sql + "FgSQL异常", e);
                //FgPubVar.g_ExceptionLos.SendException(DBname + "_SQL异常信息", e, "[" + _List[i].DbName + "]:" + _List[i].sql + "FgSQL异常");
                FgLogHelper.Write("[" + _List[i].DbName + "]:" + _List[i].sql, "FgSQL异常:" + e.Message, EnumLogPoiority.High, EnumLogType.Error);
                throw;
            }
            finally
            {
                // 清空事件链表
                Sqlcommit = null;

                // 关闭连接
                foreach (var database in obj)
                {
                    try
                    {
                        if (database.Key.conn.State != ConnectionState.Closed)
                        {
                            database.Key.conn.Close();
                        }
                    }
                    catch { }
                }
            }
        }


        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="db">Database</param>
        /// <param name="dbCommand">DbCommand</param>
        /// <param name="_CmdParms">List<IDataParameter></param>
        public void GetOutputParaVal(Database _Db, DbCommand _DbCommand, DataSet _Ds, ref List<IDataParameter> _CmdParms)
        {
            int i = 0;
            foreach (IDataParameter sp in _CmdParms)
            {
                if (sp.Direction == ParameterDirection.Output || sp.Direction == ParameterDirection.InputOutput)
                {
                    if (sp is OracleParameter)
                    {
                        if ((sp as OracleParameter).OracleType == OracleType.Cursor)
                        {
                            sp.Value = _Ds.Tables[i];
                            i++;
                            continue;
                        }
                    }
                    sp.Value = _Db.GetParameterValue(_DbCommand, sp.ParameterName);  //得到输出参数的值
                }
            }
        }

        /// <summary>
        /// sql执行后提交之前触发
        /// </summary>
        /// <param name="e"></param>
        public delegate void SqlCommit(SqlEvent e);

        /// <summary>
        /// 事件对象
        /// </summary>
        public event SqlCommit Sqlcommit;
        #endregion

        private void TimeOutLog(string _StrSql, double _Tiem)
        {
            try
            {
                var iTimeOut = FgFuncStr.NullToDouble(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);
                if (_Tiem >= iTimeOut)
                {
                    FgLogHelper.Write("~★执行时间:[" + FgFuncStr.NullToStr(_Tiem) + "秒]★ \r\t" + _StrSql);
                    new FgLogHelperPro(DBname + "_SQL超时信息").Write.Info("~★执行时间:[" + FgFuncStr.NullToStr(_Tiem) + "秒]★ \r\t" + _StrSql);
                }
                var _RunMode = FgFuncStr.NullToInt(new CacheExt().GetShareMem<DataCache>("RunMode").Parameter);
                var _RunState = FgFuncStr.GetBool(new CacheExt().GetShareMem<DataCache>("RunState").Parameter, false);
                if (_RunMode.Equals(1) && _RunState)
                {
                    var _SqlCache = "/****** 操作时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + " ******/\r/****** 执行节点：" + DBname + " ******/\r/****** 执行时间：" + FgFuncStr.NullToStr(_Tiem) + "秒 ******/\r/****** 执行语句： ******/\r" + _StrSql + "\r\r";

                    int hWnd = Win32API.FgFindWindow(@"FG6语句跟踪器").ToInt32();
                    if (hWnd != 0)
                    {
                        int len = System.Text.Encoding.Default.GetBytes(_SqlCache).Length;
                        COPYDATASTRUCT cds;
                        cds.dwData = (IntPtr)1;
                        cds.cbData = len + 1;
                        cds.lpData = _SqlCache;
                        SendMessage(hWnd, WM_COPYDATA, 0, ref cds);
                    }
                }
            }
            catch (Exception ex) { new FgLogHelperPro().Write.Error(ex); }
        }
    }
}
